package com.dhcc.bpm.modules.metadata.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.constant.FilePathConstant;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.common.utils.OpenapiGeneratorUtils;
import com.dhcc.bpm.common.utils.StringUtils;
import com.dhcc.bpm.modules.api.service.IApiService;
import com.dhcc.bpm.modules.api.service.IBaseProductService;
import com.dhcc.bpm.modules.gateway.service.IGatewayService;
import com.dhcc.bpm.modules.metadata.entity.Metadata;
import com.dhcc.bpm.modules.metadata.entity.ServerApiMetadata;
import com.dhcc.bpm.modules.metadata.service.IMetadataService;
import com.dhcc.bpm.modules.metadata.service.IProdCodeService;
import com.dhcc.bpm.modules.metadata.service.IServerApiMetadataService;
import com.dhcc.bpm.modules.metadata.vo.ServerApiMetadataVO;
import com.dhcc.bpm.modules.metadata.wrapper.ApiMetadataWrapper;
import com.dhcc.bpm.modules.system.service.IDictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.File;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;


/**
 * 接口定义数据表 控制器
 *
 * @author ccab
 * @since 2020-06-03
 */
@RestController
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
@RequestMapping("bpm-metadata/serverapimetadata")
@Api(value = "接口定义数据表", tags = "接口定义数据表接口")
public class ServerApiMetadataController extends BladeController {
    @Autowired
    private IServerApiMetadataService apiMetadataService;
    @Autowired
    private IMetadataService metadataService;
    @Autowired
    private IApiService apiService;
    @Autowired
    private IDictService dictService;
    @Autowired
    private IGatewayService gatewayService;
    @Autowired
    private IBaseProductService baseProductService;
    @Autowired
    private IProdCodeService prodCodeService;
    @Autowired
    private OpenapiGeneratorUtils openapiGeneratorUtils;

    private String path;

    @Value("${bpm.file-public-path}")
    public void setFileUploadPath(String publicPath) {
        path = publicPath + FilePathConstant.OPENAPIPATH;
    }
//    @Value("${bpm.prodCode-path}")
//    private String prodCodePath;
//    @Value("${bpm.privateKeyvalue}")
//    private String privateKeyValueSet;

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入apiMetadata")
    public R<ServerApiMetadata> detail(ServerApiMetadata apiMetadata) {
        ServerApiMetadata detail = apiMetadataService.getOne(Condition.getQueryWrapper(apiMetadata));
        return R.data(detail);
    }

    /**
     * 分页 接口定义数据表
     */
    @GetMapping("/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入apiMetadata")
    public R<List<ServerApiMetadataVO>> list(ServerApiMetadata apiMetadata, Query query) {
        IPage<ServerApiMetadata> pages = apiMetadataService.page(Condition.getPage(query), Condition.getQueryWrapper(apiMetadata));
        List<ServerApiMetadataVO> list = new ArrayList<>();
        pages.getRecords().forEach(apiMetadata1 -> {
            ServerApiMetadataVO apiMetadataVO = new ServerApiMetadataVO();
            BeanUtils.copyProperties(apiMetadata1, apiMetadataVO);
            apiMetadataVO.setParentId(apiMetadata1.getGroupId() == null ? 0L : apiMetadata1.getGroupId());
            list.add(apiMetadataVO);
        });
        return R.data(ApiMetadataWrapper.build().listNodeVO(list));
    }

    /**
     * 自定义分页 接口定义数据表
     */
    @GetMapping("/page")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页", notes = "传入apiMetadata")
    public R<IPage<ServerApiMetadataVO>> page(ServerApiMetadataVO apiMetadata, Query query) {
        IPage<ServerApiMetadataVO> pages = apiMetadataService.selectApiMetadataPage(Condition.getPage(query), apiMetadata);
        return R.data(pages);
    }

    /**
     * 新增 接口定义数据表
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入apiMetadata")
    public R save(@Valid @RequestBody ServerApiMetadata apiMetadata) {
        return R.status(apiMetadataService.save(apiMetadata));
    }

    /**
     * 修改 接口定义数据表
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入apiMetadata")
    public R update(@Valid @RequestBody ServerApiMetadata apiMetadata) {
        return R.status(apiMetadataService.updateById(apiMetadata));
    }

    /**
     * 新增或修改 接口定义数据表
     */
    @PostMapping("/submit")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增或修改", notes = "传入apiMetadata")
    public R submit(@Valid @RequestBody ServerApiMetadata apiMetadata) {
        //创建body组intype类型为body
        apiMetadata.setInType("body");
        //创建body组数据类型为object
        apiMetadata.setType("object");
        apiMetadata.setIsRequired("true");
        if (apiMetadata.getGroupId() != null && apiMetadata.getGroupId() != 0L) {
            ServerApiMetadata pApiMetadata = apiMetadataService.getById(apiMetadata.getGroupId());
            if (pApiMetadata != null) {
                apiMetadata.setGroupId(pApiMetadata.getId());
                apiMetadata.setRef(pApiMetadata.getName());
            }
            apiMetadata.setIsRequired("true");
        }
        return R.status(apiMetadataService.saveOrUpdate(apiMetadata));
    }


    /**
     * 删除 接口定义数据表
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "逻辑删除", notes = "传入ids")
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        List<Long> list = Func.toLongList(ids);
        for (Long id : list) {
            if (apiMetadataService.findByGroupId(id).size() > 0) {
                return R.fail(0001, "存在子级数据，请先删除子级数据，再删除父级数据！");
            }
        }
        return R.status(apiMetadataService.deleteLogic(Func.toLongList(ids)));
    }

    /**
     * @param opcApiIdReq
     * @param ids
     * @return org.springblade.core.tool.api.R
     * @Description 请求参数批量添加元数据
     * @Author daina
     * @Date 10:47 2020/2/22
     **/
    @PostMapping("/addReqMetadata")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "添加", notes = "opcApiIdReq,inType,ids")
    @ApiLog("接口请求参数批量添加元数据")
    @Log(title = "接口请求参数批量添加元数据", businessType = BusinessType.INSERT)
    public R addReqMetadata(@ApiParam(name = "opcApiIdReq", value = "接口id") @RequestParam Long opcApiIdReq,
                            @ApiParam(name = "inType", value = "请求参数类型") @RequestParam String inType,
                            @ApiParam(name = "parentId", value = "body请求父类id") @RequestParam Long parentId,
                            @ApiParam(value = "主键集合", required = true) @RequestParam String ids,
                            @ApiParam(value = "主键集合", required = true) @RequestParam Integer bodyType) {
        List<Long> metaIds = Func.toLongList(ids);//接收前台传过来的id集合
        List<Long> arrList = new ArrayList(metaIds);
        List<String> idsList1 = null;
        idsList1 = apiMetadataService.getApiIds(opcApiIdReq, inType, bodyType, parentId);//查询出符合条件的对象集合
        if (idsList1.size() > 1) {
            for (int i = 0; i < idsList1.size(); i++) {
                Long no1 = idsList1.get(i) == null ? null : Long.valueOf(idsList1.get(i));
                for (int j = 0; j < metaIds.size(); j++) {
                    Long no2 = metaIds.get(j);
                    if (no1 != null && no2 != null && no1.longValue() == no2.longValue()) {
                        arrList.remove(no2);
                        System.out.println(metaIds);
                    }
                }
            }
        }
        arrList.forEach(metaId -> {
            ServerApiMetadata apiMetadata = new ServerApiMetadata();
            Metadata metadata = metadataService.getById(metaId);
            apiMetadata.setMetadataId(metaId);
            apiMetadata.setApiId(opcApiIdReq);
            apiMetadata.setInType(inType);
            apiMetadata.setBodyType(bodyType);
            apiMetadata.setDefaultValue(metadata.getDefaultValue());
            apiMetadata.setDescription(metadata.getFieldName());
            apiMetadata.setFileEnum(metadata.getFieldEnum());
            if (parentId != null) {
                ServerApiMetadata pApiMetadata = apiMetadataService.getById(parentId);
                if (pApiMetadata != null) {
                    apiMetadata.setGroupId(pApiMetadata.getId());
                    apiMetadata.setRef(pApiMetadata.getName());
                    apiMetadata.setIsRequired("true");
                } else {
                    apiMetadata.setIsRequired(metadata.getIsRequired());
                }
            } else {
                apiMetadata.setGroupId(0L);
                apiMetadata.setIsRequired("true");
            }
            apiMetadata.setName(metadata.getFieldCode());
            apiMetadata.setType(metadata.getFieldType());
            apiMetadata.setTypeFormat(metadata.getTypeFormat());
            apiMetadata.setXmlName(metadata.getXmlName());
            apiMetadata.setXmlWrapped(metadata.getXmlName());
            apiMetadataService.saveOrUpdate(apiMetadata);
        });
        return R.status(true);
    }

    /**
     * @param
     * @return org.springblade.core.tool.api.R<java.util.List < com.dhcc.bpm.modules.metadata.vo.MetadataVO>>
     * @Description 获取元数据树
     * @Author daina
     * @Date 10:46 2020/2/22
     **/
    @GetMapping("/tree")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "获取元数据树", notes = "")
    @ApiLog("获取元数据树")
    @Log(title = "获取元数据树", businessType = BusinessType.SELECT)
    public R<List<ServerApiMetadataVO>> tree() {
        List<ServerApiMetadataVO> tree = apiMetadataService.tree();
        return R.data(tree);
    }

//    @GetMapping("/makeOpenApi")
//    @ApiOperationSupport(order = 9)
//    @ApiOperation(value = "生成openaapi3.0文档", notes = "apiId")
//    @ApiLog("生成openapi 3.0 文档")
//    @Log(title = "生成openapi 3.0 文档", businessType = BusinessType.SELECT)
//    public R makeOpenApi(@ApiParam(name = "apiId", value = "接口id") @RequestParam Long apiId) throws Exception {
//
//        //创建api 基本信息
//        com.dhcc.bpm.modules.api.entity.Api api = apiService.getById(apiId);
//        OpenApiParameter.OpenApiParameterBuilder openApi = OpenApiParameter.builder().info(OpenApiParameter.Info.builder().title(api.getApiEname()).description(api.getApiName()).version(api.getApiVersion()).build());
//        openApi.openapi("3.0.1");
//
//        Gateway gateway = gatewayService.getById(api.getOpcGatewayId());
//        String url = "http://" + gateway.getGatewayIp() + ":" + gateway.getGatewayPort();
//        //组装接口路径
//        ArrayList<OpenApiParameter.Servers> arrayList = new ArrayList<>();
//        arrayList.add(OpenApiParameter.Servers.builder().url(url).build());
//        openApi.servers(arrayList);
//
//        //创建请求类型 post 、get 、put 、del
//        OpenApiParameter.Method.MethodBuilder method = OpenApiParameter.Method.builder().operationId("getuserinfo").summary("summargInfo");
//
//
//        //创建query path 请求参数
//        List<ServerApiMetadata> query = apiMetadataService.findOtherByApiId(apiId);
//
//        List<OpenApiParameter.Parameters> queryParameters = new ArrayList<>();
//        for (ServerApiMetadata pa1 : query) {
//            log.info("quey ApiMetadata:{}", pa1);
//            OpenApiParameter.Parameters parameters = OpenApiParameter.Parameters.builder().description(pa1.getDescription()).in(pa1.getInType()).name(pa1.getName()).required(Boolean.valueOf(pa1.getIsRequired())).schema(OpenApiParameter.Schema.builder().type(pa1.getType()).format(pa1.getTypeFormat()).build()).build();
//            queryParameters.add(parameters);
//        }
//        method.parameters(queryParameters);
//
//        //创建json 数据对象
//        List<ServerApiMetadata> parent = apiMetadataService.findReqObjectByApiId(apiId);
//
//        HashMap<String, OpenApiParameter.Schemas> schemasMap = new HashMap<>();
//        for (ServerApiMetadata pa1 : parent) {
//            log.info("object ApiMetadata:{}", pa1);
//
//            String name = pa1.getName();
//            OpenApiParameter.Schemas.SchemasBuilder schemas = OpenApiParameter.Schemas.builder().type(pa1.getType()).xml(OpenApiParameter.Xml.builder().name(pa1.getXmlName()).build());
//
//            //添加必填参数校验
//            List<String> required = new ArrayList<>();
//
//            HashMap<String, OpenApiParameter.Schema> propertiesMap = new HashMap<>();
//
//            List<ServerApiMetadata> childern = apiMetadataService.findChildByApiId(apiId, pa1.getId());
//
//            for (ServerApiMetadata child : childern) {
//                log.info("node ApiMetadata:{}", child);
//                if ("object".equals(child.getType())) {
//                    propertiesMap.put(child.getName(), OpenApiParameter.Schema.builder().ref("#/components/schemas/" + child.getName()).build());
//                } else if ("enum".equals(child.getType())) {
//                    propertiesMap.put(child.getName(), OpenApiParameter.Schema.builder().type(child.getTypeFormat()).xml(OpenApiParameter.Xml.builder().name(child.getName()).wrapped(child.getXmlWrapped()).build()).Enum(Arrays.asList(333, 44)).build());
//                    if (Boolean.valueOf(child.getIsRequired())) {
//                        required.add(child.getName());
//                    }
//                } else if ("array".equals(child.getType())) {
//                    OpenApiParameter.Items.ItemsBuilder itemsBuilder = OpenApiParameter.Items.builder();
//                    if ("object".equals(child.getTypeFormat())) {
//                        //查出这个对应的组
//                        itemsBuilder.ref("#/components/schemas/");
//                    } else {
//                        itemsBuilder.type(child.getTypeFormat());
//                    }
//                    propertiesMap.put(child.getName(), OpenApiParameter.Schema.builder().type("array").xml(OpenApiParameter.Xml.builder().name(child.getName()).wrapped(child.getXmlWrapped()).build()).items(itemsBuilder.build()).build());
//                    if (Boolean.valueOf(child.getIsRequired())) {
//                        required.add(child.getName());
//                    }
//                } else {
//                    propertiesMap.put(child.getName(), OpenApiParameter.Schema.builder().type(child.getType()).format(child.getTypeFormat()).xml(OpenApiParameter.Xml.builder().name(child.getName()).wrapped(child.getXmlWrapped()).build()).build());
//                    if (Boolean.valueOf(child.getIsRequired())) {
//                        required.add(child.getName());
//                    }
//                }
//
//            }
//            schemas.required(required);
//            schemas.properties(propertiesMap);
//            schemasMap.put(name, schemas.build());
//        }
//
//        //json 对象构建
//
//        OpenApiParameter.Components components = OpenApiParameter.Components.builder().schemas(schemasMap).build();
//        openApi.components(components);
//
//        //组装body 参数
//        {
//            ServerApiMetadata reqRef = apiMetadataService.findParentObjectByApiId(apiId);
//
//            HashMap<String, OpenApiParameter.RequestBodySchema> schemaHashMap = new HashMap<>();
//            if (reqRef != null) {
//                schemaHashMap.put("application/json", OpenApiParameter.RequestBodySchema.builder().schema(OpenApiParameter.Schema.builder().ref("#/components/schemas/" + reqRef.getName()).build()).build());
//            }
//            OpenApiParameter.RequestBody requestBody = OpenApiParameter.RequestBody.builder().description(reqRef.getDescription()).content(schemaHashMap).required(true).build();
//
//            method.requestBody(requestBody);
//        }
//
//        //组装响应参数
//        {
//
//            ServerApiMetadata respRef = apiMetadataService.findResObjectByApiId(apiId);
//            if (respRef == null) {
//                return R.fail("api文档生成失败,响应参数不能为空!");
//            }
//
//            HashMap<String, OpenApiParameter.RequestBodySchema> schemaHashMap = new HashMap<>();
//            schemaHashMap.put("application/json", OpenApiParameter.RequestBodySchema.builder().schema(OpenApiParameter.Schema.builder().ref("#/components/schemas/" + respRef.getName()).build()).build());
//
//            HashMap<String, OpenApiParameter.Responses> mps = new HashMap<>();
//
//            mps.put("200", OpenApiParameter.Responses.builder().description("返回成功").content(schemaHashMap).build());
//
//            mps.put("500", OpenApiParameter.Responses.builder().description("返回成功").build());
//
//            method.responses(mps);
//        }
//
//        // 路径信息组装
//        {
//
//            HashMap<String, OpenApiParameter.Paths> hashMap = new HashMap<>();
//            OpenApiParameter.Paths.PathsBuilder paths = OpenApiParameter.Paths.builder();
//            //请求类型
//            switch (api.getRequestMethod()) {
//                case 1:  //1: GET
//                    paths.get(method.build());
//                    break;
//                case 2://2: POST
//                    paths.post(method.build());
//                    break;
//                case 3://3: PUT
//                    paths.put(method.build());
//                    break;
//                case 4://4: DELETE
//                    paths.delete(method.build());
//                    break;
//                default:
//                    paths.post(method.build());
//                    break;
//            }
//
//            hashMap.put(api.getApiPath(), paths.build());
//            openApi.paths(hashMap).build();
//        }
//
//        String result = JSON.toJSONString(openApi.build()).replaceAll("ref", "\\$ref");
//        log.info("result {}", result);
//
//        return R.data(result);
//    }
//
//    @PostMapping("createOpenApiYaml")
//    @ApiOperationSupport(order = 9)
//    @ApiOperation(value = "生成yaml文档、html文档和word文档", notes = "yamlMsg，APIId")
//    @ApiLog("生成yaml文档、html文档和word文档")
//    @Log(title = "生成yaml文档、html文档和word文档", businessType = BusinessType.OTHER)
//    public R createOpenApiYaml(@Valid @RequestBody ApiMetadataVO apiMetadataVO) {
//        PrintStream ps = null;
//        try {
//            com.dhcc.bpm.modules.api.entity.Api api = apiService.getById(apiMetadataVO.getApiId());
//            String pathUrl = path + "/" + api.getApiCode();
//
//            File filePath = new File(pathUrl);
//            if (!filePath.exists()) {
//                if (!filePath.mkdirs()) {
//                    return R.fail("文件创建失败!");
//                }
//            }
//            File file = new File(pathUrl + "/apiCode.yaml");
//            ps = new PrintStream(new FileOutputStream(file));
//            ps.println(apiMetadataVO.getYamlMsg());
//            ps.flush();
//
//            api.setOpenapiPath(pathUrl + "/apiCode.yaml");
//            apiService.updateById(api);
//
//            Map jsonMsg = FastJsonUtils.json2map(apiMetadataVO.getJsonMsg().replaceAll("\\$ref", "ref"));
//
//            JSONObject jsonInfo = (JSONObject)jsonMsg.get("info");
//            //api编码
//            jsonInfo.put("apiCode", api.getApiCode());
//            //api发布状态
//            jsonInfo.put("status", dictService.getValue("release_status", String.valueOf(api.getStatus())));
//            //api类别
//            jsonInfo.put("apiType", dictService.getValue("api_type", String.valueOf(api.getApiType())));
//            //api升级描述
//            jsonInfo.put("updateDes", api.getUpdateDes());
//            jsonMsg.put("info", jsonInfo);
//            //请求报文和响应报文示例内容
//            JSONObject json = new JSONObject();
//            //api请求报文示例
//            json.put("reqMsgExample", api.getReqMsgExample());
//            //api响应报文示例
//            json.put("resMsgExample", api.getResMsgExample());
//            //api报文示例
//            jsonMsg.put("message", json);
//            log.debug("jsonMsg:{}", jsonMsg);
//            json = null;
//            if (!StringUtils.isBlank(apiMetadataVO.getJsonMsg())) {
//                TemplateConfig.generate(pathUrl + "/apiCode.html", jsonMsg, "/json/api.ftl");
//                WorldUtils.htmlToWord("apiCode.doc", pathUrl + "/", FileUtils.readFileToString(new File(pathUrl + "/apiCode.html")));
//            }
//            jsonMsg = null;
//        } catch (Exception e) {
//            log.error("写入数据失败:{}", e);
//            return R.fail("生成文档失败:" + e.getMessage());
//        } finally {
//            if (ps != null) {
//                ps.close();
//            }
//
//        }
//        return R.success("生成文档成功");
//    }

    @PostMapping("downloadOpenApi")
    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "文档下载", notes = "apiId，name")
    @ApiLog("文档下载")
    @Log(title = "文档下载", businessType = BusinessType.EXPORT)
    public Resource downloadOpenApi(@Valid String apiId, String name) {
        Resource resource = null;
        try {
            com.dhcc.bpm.modules.api.entity.Api api = apiService.getById(apiId);
            String pathUrl = path + "/" + api.getApiCode();
            name = StringUtils.downLoadReplace(name);
            resource = new UrlResource(new File(pathUrl + "/" + name).toURI());
        } catch (MalformedURLException e) {
            log.error("文档下载异常：{}", e);
        }
        return resource;
    }

//    @PostMapping("createOpenApiServer")
//    @ApiOperationSupport(order = 9)
//    @ApiOperation(value = "根据yaml生成服务端代码", notes = "yaml,Server")
//    @ApiLog("根据yaml生成服务端代码")
//    @Log(title = "根据yaml生成服务端代码", businessType = BusinessType.OTHER)
//    public R createOpenApiServer(@Valid @RequestBody ApiMetadataVO apiMetadataVO) {
////        String gitPath = "https://gitee.com/zhangzexu/blog-parent.git";
//        System.out.println("---------");
//        String privateKeyValue = privateKeyValueSet;
//        com.dhcc.bpm.modules.api.entity.Api api = apiService.getById(apiMetadataVO.getApiId());
//        com.dhcc.bpm.modules.api.entity.BaseProduct baseProduct = baseProductService.getById(api.getBackserviceId());
//        List<ProdCode> prodCode = new ArrayList<>();
//        try {
//            prodCode = prodCodeService.getProdCode(baseProduct.getProductName());
//            System.out.println("++++++"+prodCode);
//            if (prodCode.isEmpty()) {
//                return R.fail("api对应产品查询失败");
//            }
//
//            String gitPath = prodCode.get(0).getGitAddress();
//            String gitUsername = prodCode.get(0).getGituserName();
//            String gitPassword = ProdCodeController.decrypt(prodCode.get(0).getGitPassword(), privateKeyValue);
//
//
//            String localPath = "";
//
//            if (!prodCodePath.endsWith("/")) {
//                localPath = prodCodePath + "/";
//            } else {
//                localPath = prodCodePath;
//            }
//
//            String[] s = gitPath.split("/");
//            //代码的项目名称
//            String project = s[s.length - 1].replace(".git", "");
//
//            System.out.println(project);
//
//            localPath = localPath + project;
//
//
//
//            String pathUrl = path + "/" + api.getApiCode() + "/apiCode.yaml";
//            log.info("该apiyaml 文档的位置为:{}", pathUrl);
//
//            R r = openapiGeneratorUtils.makeClient(pathUrl, localPath+"Client", prodCode.get(0).getGroupId(), prodCode.get(0).getArtifactId(), prodCode.get(0).getArtifactVersion(), prodCode.get(0).getInvokerPackage(), prodCode.get(0).getInvokerPackage(), prodCode.get(0).getInvokerPackage());
//
//            if (StringUtils.isBlank(r.getMsg())) {
//                r.setMsg("JAVA SDK生成失败");
//                return r;
//            } else {
//                log.info("JAVA SDK 生成成功");
//            }
//            r = JGitUtil.pull(gitUsername, gitPassword, "develop", localPath);
//            if (!r.isSuccess()) {
//                return r;
//            }
//
//            r = openapiGeneratorUtils.makeOpenapiServer(pathUrl, localPath, prodCode.get(0).getGroupId(), prodCode.get(0).getArtifactId(), prodCode.get(0).getArtifactVersion(), prodCode.get(0).getInvokerPackage(), prodCode.get(0).getInvokerPackage(), prodCode.get(0).getInvokerPackage());
//
//            if (StringUtils.isBlank(r.getMsg())) {
//                r.setMsg("服务端代码生成失败");
//                return r;
//            } else {
//                if (!r.getMsg().contains(".openapi-generator/VERSION")) {
//                    return r;
//                }
//            }
//
//            //创建代码
//            r = JGitUtil.commitAndPush(gitUsername, gitPassword, ".", api.getApiName() + " server代码创建", localPath);
//            if (!r.isSuccess()) {
//                return r;
//            }
//        } catch (Exception e) {
//            log.error("代码生成失败:{}", e);
//            return R.fail("代码生成失败");
//        }
//
//        return R.success("server端代码生成成功");
//    }

    final static Base64.Encoder encoder = Base64.getEncoder();
    final static Base64.Decoder decoder = Base64.getDecoder();

    /**
     * 给字符串加密
     *
     * @param text
     * @return
     */
    public static String encode(String text) {
        return encoder.encodeToString(text.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 将加密后的字符串进行解密
     *
     * @param encodedText
     * @return
     */
    public static String decode(String encodedText) {
        return new String(decoder.decode(encodedText), StandardCharsets.UTF_8);
    }


}
